package controllers

import (
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

type JobDtlController struct {
	beego.Controller
}

type JobDtlListReq struct {
	JobDate   string   `form:"jobDate"`
	JobId     string   `form:"jobId"`
	JobStatus []string `form:"jobStatus"`
	Draw      int64    `form:"draw"`
	Start     int      `form:"start"`
	Length    int      `form:"length"`
}

type JobDtlListRsp struct {
	Draw            int64        `json:"draw"`
	RecordsTotal    int64        `json:"recordsTotal"`
	RecordsFiltered int64        `json:"recordsFiltered"`
	Data            []*TblJobDtl `json:"data"`
	Error           string       `json:"error"`
}

func (c *JobDtlController) Get() {
	var (
		err error
		req = new(JobDtlListReq)
		rsp = new(JobDtlListRsp)
	)

	_ = c.ParseForm(req)
	_ = c.Ctx.Input.Bind(&req.JobStatus, "jobStatus")

	o := orm.NewOrm()

	rsp.RecordsTotal, err = o.QueryTable("tbl_job_dtl").
		Filter("job_date", req.JobDate).Filter("job_id__contains", req.JobId).Filter("job_status__in", req.JobStatus).Count()
	if err != nil {
		rsp.Error = err.Error()
		goto Finish
	}

	_, err = o.QueryTable("tbl_job_dtl").
		Filter("job_date", req.JobDate).Filter("job_id__contains", req.JobId).Filter("job_status__in", req.JobStatus).
		OrderBy("-create_time").Limit(req.Length).Offset(req.Start).All(&rsp.Data)
	if err != nil && err != orm.ErrNoRows {
		rsp.Error = err.Error()
		goto Finish
	}

	rsp.Draw = req.Draw
	rsp.RecordsFiltered = rsp.RecordsTotal

	for _, row := range rsp.Data {
		row.JobDate = row.JobDate[:10]
		row.CreateTime = row.CreateTime[:19]
		row.UpdateTime = row.UpdateTime[:19]
	}

	if len(rsp.Data) == 0 {
		rsp.Data = make([]*TblJobDtl, 0)
	}

Finish:
	c.Data["json"] = rsp
	c.ServeJSON()
}
